package com.xidian.zhiancloud.service.equipFacility;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xidian.zhiancloud.dao.*;
import com.xidian.zhiancloud.dao.syset.PositionMapper;
import com.xidian.zhiancloud.dao.syset.SysUserMapper;
import com.xidian.zhiancloud.dao.syset.usermanage.OrganizationMapper;
import com.xidian.zhiancloud.dto.equipFacility.DefendPlanMakeDTO;
import com.xidian.zhiancloud.enums.GeneralResponseEnums;
import com.xidian.zhiancloud.exception.CustomizeException;
import com.xidian.zhiancloud.model.*;
import com.xidian.zhiancloud.model.syset.Organization;
import com.xidian.zhiancloud.model.syset.PositionList;
import com.xidian.zhiancloud.model.syset.SysUser;
import com.xidian.zhiancloud.dto.equipFacility.DefendObjects;
import com.xidian.zhiancloud.qo.equipFacility.DefendPlanMakeQO;
import com.xidian.zhiancloud.vo.equipFacility.DefendObjectVO;
import com.xidian.zhiancloud.vo.equipFacility.DefendPlanMakeDTOVO;
import com.xidian.zhiancloud.vo.equipFacility.DefendPlanMakeVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.Array;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 维护计划制定
 * @Author: 任启亮
 * @Date: 2020/11/11
 */
@Service
public class DefendPlanMakeService extends ServiceImpl<DefendPlanMakeMapper, DefendPlanMake> implements IService<DefendPlanMake> {

    @Autowired
    private DefendPlanMakeMapper defendPlanMakeMapper;
    @Autowired
    private DefendObjectMapper defendObjectMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private OrganizationMapper organizationMapper;
    @Autowired
    private EqFacMngMapper eqFacMngMapper;
    @Autowired
    private DefendPlanItemMapper defendPlanItemMapper;

    @Autowired
    private PositionMapper positionMapper;

    /**
     * 添加维护计划
     * @param defendPlanMakeDTO
     * @return
     */
    @Transactional(rollbackFor = {RuntimeException.class, Error.class, CustomizeException.class})
    public Boolean add(DefendPlanMakeDTO defendPlanMakeDTO){
        DefendPlanMake defendPlanMake = defendPlanMakeDTO.getDefendPlanMake();
        List<DefendObjects> defendObjects = defendPlanMakeDTO.getDefendObjects();

        Set<String> set = new HashSet<>();

        //获取检修人姓名
        String name = "";
        for (DefendObjects obj : defendObjects) {
            List<SysUser> defenders = obj.getDefenders();
            for (SysUser user : defenders) {
                SysUser sysUser = sysUserMapper.selectById(user.getId());
                if(sysUser != null){
                    if(!set.contains(sysUser.getName())){
                        set.add(sysUser.getName());
                        name += sysUser.getName() + ",";
                    }
                }

            }
        }

        //插入检修计划
        defendPlanMake.setDefender(name);
        int ret = defendPlanMakeMapper.insert(defendPlanMake);
        if(ret == 0){
            throw new CustomizeException(GeneralResponseEnums.ADD_FAILED);
        }

        //获取检修对象
        for (DefendObjects obj : defendObjects) {
            DefendObject defendObject = new DefendObject();
            List<SysUser> defenders = obj.getDefenders();
            String ids = "";
            for (SysUser defender : defenders) {
                ids += defender.getId() + ",";
            }
            defendObject.setDefender(ids);
            defendObject.setEqFacId(obj.getEqFacMng().getId());
            defendObject.setDefendPlanMakeId(defendPlanMake.getId());

            //添加检修对象
            int insert = defendObjectMapper.insert(defendObject);
            if(insert == 0){
                throw new CustomizeException(GeneralResponseEnums.ADD_FAILED);
            }
        }

        return true;
    }

    /**
     * 更新维护计划
     * @param defendPlanMakeDTO
     * @return
     */
    @Transactional(rollbackFor = {RuntimeException.class, Error.class, CustomizeException.class})
    public Boolean patchById(DefendPlanMakeDTO defendPlanMakeDTO){

        DefendPlanMake defendPlanMake = defendPlanMakeDTO.getDefendPlanMake();
        List<DefendObjects> defendObjects = defendPlanMakeDTO.getDefendObjects();

        Set<String> set = new HashSet<>();
        //重新获取维护人姓名
        String name = "";
        for (DefendObjects obj : defendObjects) {
            List<SysUser> defenders = obj.getDefenders();
            for (SysUser defender : defenders) {
                SysUser user = sysUserMapper.selectById(defender.getId());
                if(!set.contains(user.getName())){
                    set.add(user.getName());
                    name += user.getName() + ",";
                }
            }
        }
        defendPlanMake.setDefender(name);

        //更新维护计划
        int ret = defendPlanMakeMapper.updateById(defendPlanMake);
        if(ret == 0){
            throw new CustomizeException(GeneralResponseEnums.UPDATE_FAILED);
        }

        //删除原有维护对象
        LambdaQueryWrapper<DefendObject> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(DefendObject::getDefendPlanMakeId,defendPlanMake.getId());
        defendObjectMapper.delete(queryWrapper);

        //重新添加维护对象
        for (DefendObjects obj : defendObjects) {
            DefendObject defendObject = new DefendObject();
            defendObject.setEqFacId(obj.getEqFacMng().getId());
            defendObject.setDefendPlanMakeId(defendPlanMake.getId());

            String ids = "";
            List<SysUser> defenders = obj.getDefenders();
            for (SysUser defender : defenders) {
                ids += defender.getId();
            }

            defendObject.setDefender(ids);

            defendObjectMapper.insert(defendObject);
        }

        return true;
    }

    /**
     * 删除维护计划
     * @param ids
     * @return
     */
    @Transactional(rollbackFor = {RuntimeException.class, Error.class, CustomizeException.class})
    public Boolean delete(Long[] ids){

        if(ids == null || ids.length == 0){
            return false;
        }

        for (Long id : ids) {
            //删除维护计划
            int ret = defendPlanMakeMapper.deleteById(id);
            if(ret == 0){
                throw new CustomizeException(GeneralResponseEnums.DELETE_FAILED);
            }

            //删除维护对象
            LambdaQueryWrapper<DefendObject> queryWrapper = Wrappers.lambdaQuery();
            queryWrapper.eq(DefendObject::getDefendPlanMakeId,id);
            int delete = defendObjectMapper.delete(queryWrapper);
            if(delete == 0){
                throw new CustomizeException(GeneralResponseEnums.DELETE_FAILED);
            }
        }

        return true;
    }

    /**
     * 根据id获取维护计划信息
     * @param id 维护计划id
     * @return
     */
    public DefendPlanMakeVO getById(Long id){
        DefendPlanMakeVO vo = new DefendPlanMakeVO();

        //获取维修计划
        DefendPlanMake defendPlanMake = defendPlanMakeMapper.selectById(id);
        if(defendPlanMake == null){
            throw new CustomizeException(GeneralResponseEnums.GET_FAILED);
        }

        BeanUtils.copyProperties(defendPlanMake,vo);

        //查询创建人
        SysUser creator = sysUserMapper.selectById(defendPlanMake.getCreator());
        vo.setCreateName(creator == null ? "该用户不存在" : creator.getName());

        //查询组织部门
        Organization organization = organizationMapper.selectById(defendPlanMake.getOrgId());
        vo.setOrganizationName(organization == null ?  "该部门不存在" : organization.getName());

        //查询维护对象
        LambdaQueryWrapper<DefendObject> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(DefendObject::getDefendPlanMakeId,id);
        List<DefendObject> defendObjects = defendObjectMapper.selectList(queryWrapper);

        //维护对象列表
        List<DefendObjectVO> list = new ArrayList<>();

        for (DefendObject obj : defendObjects) {
            DefendObjectVO defendObjectVO = new DefendObjectVO();

            //设备设施 维护人
            EqFacMng eqFacMng = eqFacMngMapper.selectById(obj.getEqFacId());

            if(eqFacMng != null){
                BeanUtils.copyProperties(eqFacMng,defendObjectVO);
            }else{
                continue;
            }

            //查询设备设施区域位置
            PositionList positionList = positionMapper.selectById(eqFacMng.getPosition());
            defendObjectVO.setPositionName(positionList==null ? "该区域位置不存在" : positionList.getName());

            //查询管辖部门名称
            Organization organization1 = organizationMapper.selectById(eqFacMng.getMngCtrDeptId());
            defendObjectVO.setDepartmentName(organization1==null ? "该部门不存在" : organization1.getName());

            String defender = obj.getDefender();
            String name = "";

            long[] array = Arrays.stream(defender.split(",")).mapToLong(Long::parseLong).toArray();
            for (long i : array) {
                SysUser sysUser = sysUserMapper.selectById(i);
                if(sysUser != null){
                    name += sysUser.getName() + ",";
                }
            }
            defendObjectVO.setDefenderId(defender);
            defendObjectVO.setDefenderName(name);
            list.add(defendObjectVO);
        }
        
        vo.setDefendObjectVOList(list);

        return vo;
    }

    /**
     * 列表查询
     * @param defendPlanMakeQO
     * @return
     */
    public IPage<DefendPlanMakeVO> getListByQO(DefendPlanMakeQO defendPlanMakeQO) {

        Page<DefendPlanMakeVO> page = new Page<>(defendPlanMakeQO.getCurrent(), defendPlanMakeQO.getSize());

        //排序
        OrderItem orderItem = new OrderItem();
        orderItem.setColumn("create_time").setAsc(false);
        page.getOrders().add(orderItem);

        IPage<DefendPlanMakeVO> ans = defendPlanMakeMapper.selectByQO(page, defendPlanMakeQO);

        return ans;
    }

    /**
     * 发布接口
     * @param id
     * @return
     */
    public Boolean submit(Long id){

        DefendPlanMake defendPlanMake = defendPlanMakeMapper.selectById(id);
        defendPlanMake.setStatus(1);

        int ret = defendPlanMakeMapper.updateById(defendPlanMake);
        if(ret == 0){
            throw new CustomizeException(GeneralResponseEnums.SUBMIT_FAILED);
        }

        return true;
    }

}
